// app.js
import log from "./utils/log"
const { toast, promisify } = require("./utils/util")
App({
  onLaunch() {
    if (wx.canIUse('getWindowInfo')) {
      const windowInfo = wx.getWindowInfo()
      this.globalData.StatusBar = windowInfo.statusBarHeight;
      let custom = wx.getMenuButtonBoundingClientRect();
      this.globalData.Custom = custom;  
      this.globalData.CustomBar = custom.bottom + custom.top - windowInfo.statusBarHeight;
    } else {
      wx.getSystemInfo({
        success: e => {
          console.log(1, e)
          this.globalData.StatusBar = e.statusBarHeight;
          let custom = wx.getMenuButtonBoundingClientRect();
          this.globalData.Custom = custom;  
          this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        }
      })
    }
    this.globalData.ACCESSTOKEN = wx.getStorageSync('ACCESSTOKEN')

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res.code)
      }
    })
  },
  onShow() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('res.hasUpdate====')
          updateManager.onUpdateReady(function () {
              wx.showModal({
                  title: '更新提示',
                  content: '新版本已经准备好，是否重启应用？',
                  success: function (res) {
                      if (res.confirm) {
                          updateManager.applyUpdate()
                      }
                  }
              })
          })
          updateManager.onUpdateFailed(function () {
              // 新的版本下载失败
              wx.showModal({
                  title: '已经有新版本了哟~',
                  content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
              })
          })
        }
      })
    };
    this.globalData.ACCESSTOKEN = wx.getStorageSync('ACCESSTOKEN')
  },

  getWxcode() {
    return new Promise(async (resolve, reject) => {
      let wxCode = await promisify(wx.login)().catch((err) => {
        wx.hideLoading()
        wx.showToast({
          title: "请授权，否则将无法正常使用小程序",
          icon: 'none'
        })
        log.error('用户获取code失败',err)
        reject(err)
      })
      if(!wxCode) return
      console.log('获取code',wxCode.code);
      log.warn('用户获取code成功')
      resolve(wxCode.code)
    })
  },
  globalData: {
    ACCESSTOKEN: '',
    userInfo: {
      partyOrganizationSerialNumber: "PartyOrg0000022",
      iDCardNumber: "230811198602258087",
      partyMemberSerialNumber: 'PMI000000000013',
      username: '13236743199'
    },
    StatusBar: 0,
    Custom: null,
    CustomBar: 0,
    details: {}
  }
})
